<?php

namespace App\Services\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Meeting;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;
use Hyperf\Contract\LengthAwarePaginatorInterface;

class MeetingDao
{
    /**
     * @param int $id
     * @return Builder|Model|object|null
     */
    public function findMeetingById(int $id): ?Meeting
    {
        $model = Meeting::query()->where('id', '=', $id)->first();
        if (empty($model)) {
            throw new BusinessException(ErrorCode::MEETING_NOT_EXIST, ErrorCode::getMessage(ErrorCode::MEETING_NOT_EXIST));
        }
        return $model;
    }

    /**
     * @param array $ids
     * @return Builder[]|Collection
     */
    public function findMeetingByIds(array $ids)
    {
        return Meeting::query()->whereIn('id', $ids)->get();
    }

    /**
     * note: 查找活动-正常返回不抛出异常
     * @param int $id
     * created by: lhw at 14/1/2022 9:21 下午
     * @return Builder|Model|object|null
     */
    public function socketFindMeetingById(int $id): ?Meeting
    {
        return Meeting::query()->where('id', '=', $id)->first();
    }

    /**
     * note:获取所有活动信息
     * @param int $userId
     * @param int $limit
     * created by: lhw at 10/1/2022 9:01 下午
     * @return LengthAwarePaginatorInterface
     */
    public function findAllMeetingsByUserId(int $userId, int $limit = 10): LengthAwarePaginatorInterface
    {
        return Meeting::query()->where('user_id', '=', $userId)->orderByDesc('id')
                ->paginate($limit);
    }

    /**
     * @param int $id
     * @param false $throw
     * @return Builder|Model|object|null
     */
    public function first(int $id, bool $throw = false): ?Meeting
    {
        $model = Meeting::query()->where('id', $id)->first();

        if (empty($model) && $throw) {
            throw new BusinessException(ErrorCode::MEETING_NOT_EXIST, ErrorCode::getMessage(ErrorCode::MEETING_NOT_EXIST));
        }

        return $model;
    }
}
